<?php
$db_connect = mysqli_connect("localhost", "root", "", "battleofthemages");
session_start();

require_once("User.php");
if(isset($_POST['action'])){
	if($_POST['action'] == "login"){
		if(($_POST['username'] == "") || (!preg_match('/^[A-Za-z0-9-_]{3,15}$/', $_POST['username']))){
			echo "userError";
		}else if(($_POST['password'] == "") || (!preg_match("/^[A-Za-z0-9-_]{3,15}$/", $_POST['password']))){
			echo "passError";
		}else{
			$username = $_POST['username'];
			$password = $_POST['password'];
			$userQuery = "SELECT username, password, rank_id FROM user WHERE username=\"$username\"";
			$result = mysqli_query($db_connect, $userQuery);
			if(mysqli_num_rows($result) > 0){
				$userConfirmQuery = "SELECT username, password, rank_id FROM user WHERE username=\"$username\" AND password=\"$password\"";
				$resultConfirm = mysqli_query($db_connect, $userConfirmQuery);
				if(mysqli_num_rows($resultConfirm) > 0){
					$row = mysqli_fetch_assoc($resultConfirm);
					$user = new User($username, $row['rank_id']);
                    $onlineQuery = "UPDATE user SET is_online=1 WHERE username=\"$username\"";
                    mysqli_query($db_connect, $onlineQuery);
					$_SESSION['user'] = serialize($user);
					echo "redirect";
				}else{
					echo "passError";
				}	
			}else{
				echo "userError";
			}
		}
	}else if($_POST['action'] == "register_button"){
		echo "register_button";
	}else if($_POST['action'] == "register"){
		$username = $_POST['username'];
		$userQuery = "SELECT `username`, `password`, `rank_id` FROM `user` WHERE username=\"$username\"";
		$result = mysqli_query($db_connect, $userQuery);
		if(mysqli_num_rows($result) > 0){
			echo "userError";
		}else if(($_POST['username'] == "") || (!preg_match('/^[A-Za-z0-9]{3,15}$/', $_POST['username']))){
			echo "userError";
		}else if(($_POST['mail'] == "") || (!preg_match("/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/", $_POST['mail']))){
			echo "mailError";
		}else if($_POST['password'] == "" || (!preg_match("/^[A-Za-z0-9-_]{3,15}$/", $_POST['password']))){
			echo "passError";
		}else if($_POST['password'] != $_POST['repeatPass']){
			echo "repeatPassError";
		}else{
			$username = $_POST['username'];
			$password = $_POST['password'];
			$email = $_POST['mail'];

			$query = "INSERT INTO user(username, password, email, rank_id) VALUES (\"$username\",\"$password\",\"$email\",1)";
			$result = mysqli_query($db_connect, $query);

			$user = new User($username, 1);
			$_SESSION['user'] = serialize($user);
			echo "redirect";
		}
	}else if($_POST['action'] == "logout"){
        $user = unserialize($_SESSION['user']);
        $username = $user->getUsername();
		session_destroy();
        $logoutQuery = "UPDATE user SET is_online=0 WHERE username=\"$username\"";
        $result = mysqli_query($db_connect, $logoutQuery);
		echo "logout";
	}
}else{
	echo "ERROR!";
}
mysqli_close($db_connect);
?>